package com.utcs.modules.resource.basic.utils;



import com.utcs.common.utils.CacheUtils;
import com.utcs.common.utils.SpringContextHolder;
import com.utcs.modules.resource.basic.dao.DepartmentDao;
import com.utcs.modules.resource.basic.dao.MenuDao;
import com.utcs.modules.resource.basic.dao.UserDao;
import com.utcs.modules.resource.basic.entity.Department;
import com.utcs.modules.resource.basic.entity.Menu;
import com.utcs.modules.resource.basic.entity.User;
import com.utcs.modules.resource.basic.security.SystemAuthorizingRealm.Principal;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import java.util.List;

/**
 * Created by SWan on 2017/4/26.
 *用户工具类
 */
public class UserUtils {

    private static MenuDao menuDao = SpringContextHolder.getBean(MenuDao.class);
    private static DepartmentDao departmentDao = SpringContextHolder.getBean(DepartmentDao.class);
    private static UserDao userDao = SpringContextHolder.getBean(UserDao.class);

    public static final String USER_CACHE = "userCache";
    public static final String USER_CACHE_ID_ = "id_";
    public static final String USER_CACHE_NAME_ = "ln";
    public static final String USER_CACHE_LIST_BY_OFFICE_ID_ = "oid_";

    public static final String CACHE_AUTH_INFO = "authInfo";
    public static final String CACHE_ROLE_LIST = "roleList";
    public static final String CACHE_MENU_LIST = "menuList";

    /**
     * 根据ID获取用户
     * @param id
     * @return 取不到返回null
     */
    public static User get(Integer id){
        User user = (User)CacheUtils.get(USER_CACHE, USER_CACHE_ID_ + id);
        if (user ==  null){
            user = userDao.get(id);
            if (user == null){
                return null;
            }
        //    user.setRoleList(roleDao.findList(new Role(user)));
            CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
            CacheUtils.put(USER_CACHE, USER_CACHE_NAME_ + user.getName(), user);
        }
        return user;
    }
    /**
     * 获取当前用户
     * @return 取不到返回 new User()
     */
    public static User getUser(){
        Principal principal = getPrincipal();
        if (principal!=null){
            User user = get(principal.getId());
            if (user != null){
                return user;
            }
            return new User();
        }
        // 如果没有登录，则返回实例化空的User对象。
        return new User();
    }

    /**
     * 根据用户名获取用户
     * @param name
     * @return 取不到返回null
     */
    public static User getByName(String name){
        User user = (User) CacheUtils.get(USER_CACHE, USER_CACHE_NAME_ + name);
        if (user == null){
            user = userDao.getByName(new User(null, name));
            if (user == null){
                return null;
            }
           // user.setRoleList(roleDao.findList(new Role(user)));
            CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
            CacheUtils.put(USER_CACHE, USER_CACHE_NAME_ + user.getName(), user);
        }
        return user;
    }
    /**
     * 获取当前用户授权菜单
     * @return
     */
    public static List<Menu> getMenuList(){
        List<Menu> menuList = (List<Menu>)getCache(CACHE_MENU_LIST);
        if (menuList == null){
            User user = getUser();
            if (user.isAdmin()){
                menuList = menuDao.findAllList(new Menu());
            }else{
                Menu m = new Menu();
                m.setUserId(user.getId());
                menuList = menuDao.findByUserId(m);
            }
            putCache(CACHE_MENU_LIST, menuList);
        }
        return menuList;
    }


    /**
     * 获取当前用户有权限访问的部门
     * @return
     */
    public static List<Department> getDepartmentAllList(){
        List<Department> departmentList = departmentDao.findAllList(new Department());
        return departmentList;
    }

    /**
     * 获取授权主要对象
     */
    public static Subject getSubject(){
        return SecurityUtils.getSubject();
    }

    /**
     * 获取当前登录者对象
     */
    public static Principal getPrincipal(){
        try{
            Subject subject = SecurityUtils.getSubject();
            Principal principal = (Principal)subject.getPrincipal();
            if (principal != null){
                return principal;
            }
//			subject.logout();
        }catch (UnavailableSecurityManagerException e) {

        }catch (InvalidSessionException e){

        }
        return null;
    }

    public static Session getSession(){
        try{
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession(false);
            if (session == null){
                session = subject.getSession();
            }
            if (session != null){
                return session;
            }
//			subject.logout();
        }catch (InvalidSessionException e){

        }
        return null;
    }

    // ============== User Cache ==============

    public static Object getCache(String key) {
        return getCache(key, null);
    }

    public static Object getCache(String key, Object defaultValue) {
//		Object obj = getCacheMap().get(key);
        Object obj = getSession().getAttribute(key);
        return obj==null?defaultValue:obj;
    }

    public static void putCache(String key, Object value) {
//		getCacheMap().put(key, value);
        getSession().setAttribute(key, value);
    }

    public static void removeCache(String key) {
//		getCacheMap().remove(key);
        getSession().removeAttribute(key);
    }
}
